package org.ccay.log.connection.impl;

import java.sql.Connection;
import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.ccay.core.ioc.Ccay;
import org.ccay.log.connection.IDatabaseConnectionLog;

/**
 * 数据库连接拦截器
 * @author chaowangbang
 *
 */
@Intercepts({
		@Signature(type = Executor.class, method = "query", args = {
				MappedStatement.class, Object.class, RowBounds.class,
				ResultHandler.class }),
		@Signature(type = Executor.class, method = "update", args = {
				MappedStatement.class, Object.class }) })
public class DatabaseConnectionLogInterceptor implements Interceptor {
	
	private IDatabaseConnectionLog connectionLog;
	
	/**
	 * 对connection进行拦截
	 * (non-Javadoc)
	 * @see org.apache.ibatis.plugin.Interceptor#intercept(org.apache.ibatis.plugin.Invocation)
	 */
	public Object intercept(Invocation invocation) throws Throwable {
		if(!ConnectionLogStatusManager.isLogEnabled()){
			return invocation.proceed();
		}
		
		//读取数据字典Connection对象开关操作
		if(connectionLog == null){
			connectionLog =Ccay.getContext().getBean("connectionLog", IDatabaseConnectionLog.class);
		}
		Executor executor = (Executor) invocation.getTarget();
		
		Connection con = executor.getTransaction().getConnection();
		if(null != con){
			connectionLog.log(con);
		}
		
		//清空连接
		//connectionLog.clearLog(executor.getTransaction().getConnection());
		return  invocation.proceed();
	}

	/* (non-Javadoc)
	 * @see org.apache.ibatis.plugin.Interceptor#plugin(java.lang.Object)
	 */
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	/* (non-Javadoc)
	 * @see org.apache.ibatis.plugin.Interceptor#setProperties(java.util.Properties)
	 */
	public void setProperties(Properties arg0) {

	}

}
